package cn.jietuo.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2019-10-04
 * @description: 懒汉式
 *
 * <pre>
 *     可以使用synchornized解决，但是也带来了效率的降低
 * </pre>
 */
public class Singleton_lazy4 {

    private static volatile Singleton_lazy4 INSTANCE; // volatile 防止指令重拍序，线程间可见

    private Singleton_lazy4() {
        if (INSTANCE != null) {
            throw new RuntimeException("单例不允许多个实例");
        }
    }

    private static Singleton_lazy4 getInstance() {
        if (INSTANCE == null) {
            // 双重检查
            synchronized (Singleton_lazy4.class) {
                if (INSTANCE == null) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new Singleton_lazy4();
                }
            }
        }
        return INSTANCE;
    }


    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//        for (int i = 0; i < 10000; i++) {
//            new Thread(() -> System.out.println(Singleton_lazy4.getInstance().hashCode())).start();
//        }
        Constructor<Singleton_lazy4> declaredConstructor = Singleton_lazy4.class.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Singleton_lazy4 singleton_lazy4 = declaredConstructor.newInstance();

        Singleton_lazy4 instance = Singleton_lazy4.INSTANCE;
        System.out.println(singleton_lazy4 == instance);

    }
}
